package com.hong.utils.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @Auther: Administrator
 * @Date: 2018/7/23 11:26
 * @Description:
 */
public class SemaphoreExample2 {
    /**
     * connection pool
     * when get the not  available connection/policy
     * 1.Get 1000MS the throw execption
     * 2.blocking
     * 3.discard
     * 4.Get the throw execption
     *
     * @param args
     */
    public static void main(String[] args) throws InterruptedException {

        final Semaphore semaphore = new Semaphore(2);

        for (int i = 0;i<2;i++){
            new Thread(){
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+" in ");
                    try {
                        semaphore.acquire(1);
                        System.out.println(Thread.currentThread().getName()+" get the semaphore. ");
                        TimeUnit.SECONDS.sleep(5);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }finally {
                        semaphore.release(1);
                    }
                    System.out.println(Thread.currentThread().getName()+ " out ");
                }
            }.start();

            while (true){
                /*可用的*/
                System.out.println("AP-"+semaphore.availablePermits());
                /*当前有多少个线程block住了*/
                System.out.println("QL-"+semaphore.getQueueLength());
                System.out.println("=========================");
                TimeUnit.SECONDS.sleep(1);
            }
        }
    }


}
